<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">
<meta name="referrer" content="same-origin">
<meta name="referrer" content="no-referrer" />








<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="RocketMQ之旅," />










<meta name="description" content="命令行启动&amp;emsp;&amp;emsp;先从官方的一段启动命令开始我们的旅程：123&amp;gt; nohup sh bin/mqbroker -n localhost:9876 &amp;amp;&amp;gt; tail -f ~/logs/rocketmqlogs/broker.log The broker[%s, 172.30.30.233:10911] boot success... mqbroker脚本放在dis">
<meta name="keywords" content="RocketMQ之旅">
<meta property="og:type" content="article">
<meta property="og:title" content="RocketMQ之旅（六）broker启动">
<meta property="og:url" content="http://yoursite.com/2018/12/17/RocketMQ之旅（六）broker启动/index.html">
<meta property="og:site_name" content="矩阵编程">
<meta property="og:description" content="命令行启动&amp;emsp;&amp;emsp;先从官方的一段启动命令开始我们的旅程：123&amp;gt; nohup sh bin/mqbroker -n localhost:9876 &amp;amp;&amp;gt; tail -f ~/logs/rocketmqlogs/broker.log The broker[%s, 172.30.30.233:10911] boot success... mqbroker脚本放在dis">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-10-24T16:22:00.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="RocketMQ之旅（六）broker启动">
<meta name="twitter:description" content="命令行启动&amp;emsp;&amp;emsp;先从官方的一段启动命令开始我们的旅程：123&amp;gt; nohup sh bin/mqbroker -n localhost:9876 &amp;amp;&amp;gt; tail -f ~/logs/rocketmqlogs/broker.log The broker[%s, 172.30.30.233:10911] boot success... mqbroker脚本放在dis">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2018/12/17/RocketMQ之旅（六）broker启动/"/>





  <title>RocketMQ之旅（六）broker启动 | 矩阵编程</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?7d29e6fba8e07d1a8af2414a20e5f2a6";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">矩阵编程</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-主页">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-主页"></i> <br />
            
            主页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-分类"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-所有文章">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-文章"></i> <br />
            
            所有文章
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2018/12/17/RocketMQ之旅（六）broker启动/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="matrix">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="矩阵编程">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">RocketMQ之旅（六）broker启动</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-12-17T22:22:41+08:00">
                2018-12-17
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/RocketMQ之旅/" itemprop="url" rel="index">
                    <span itemprop="name">RocketMQ之旅</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2018/12/17/RocketMQ之旅（六）broker启动/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count"
                        data-disqus-identifier="2018/12/17/RocketMQ之旅（六）broker启动/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h4 id="命令行启动"><a href="#命令行启动" class="headerlink" title="命令行启动"></a>命令行启动</h4><p>&emsp;&emsp;先从官方的一段启动命令开始我们的旅程：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&gt; nohup sh bin/mqbroker -n localhost:<span class="number">9876</span> &amp;</span><br><span class="line">&gt; tail -f ~/logs/rocketmqlogs/broker.log </span><br><span class="line">The broker[%s, <span class="number">172.30</span>.30.233:<span class="number">10911</span>] boot success...</span><br></pre></td></tr></table></figure></p>
<p>mqbroker脚本放在distribution模块的bin目录下。贴一下该脚本的启动命令语句：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">sh $&#123;ROCKETMQ_HOME&#125;/bin/runbroker.sh org.apache.rocketmq.broker.BrokerStartup $@</span><br></pre></td></tr></table></figure></p>
<p>从这句sh命令可知，mqbroker脚本主要是启动broker模块的<strong>BrokerStartup</strong>，<strong>BrokerStartup</strong>是整个broker的入口：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">    start(createBrokerController(args));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<a id="more"></a>
<p><strong>createBrokerController()</strong>创建<strong>BrokerController</strong>，并根据命令行配置运行参数，调用<strong>BrokerController</strong>的<strong>initialize()</strong>进行初始化。</p>
<h4 id="初始化"><a href="#初始化" class="headerlink" title="初始化"></a>初始化</h4><p>&emsp;&emsp;<strong>initialize()</strong>的函数比较长，所以我把它拆分成几个部分：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">initialize</span><span class="params">()</span> <span class="keyword">throws</span> CloneNotSupportedException </span>&#123;</span><br><span class="line">    <span class="comment">// 1. 加载ConfigManager和MessageStore</span></span><br><span class="line">    <span class="comment">// 2. 初始化NettyRemotingServer</span></span><br><span class="line">    <span class="comment">// 3. 初始化线程池</span></span><br><span class="line">    <span class="comment">// 4. 为NettyRemotingServer注册处理器</span></span><br><span class="line">    <span class="comment">// 5. 开启定时任务</span></span><br><span class="line">    <span class="comment">// 6. tls模式的文件监听</span></span><br><span class="line">    <span class="comment">// 7. 初始化事务线程</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>先看第一部分加载ConfigManager和MessageStore：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">initialize</span><span class="params">()</span> <span class="keyword">throws</span> CloneNotSupportedException </span>&#123;</span><br><span class="line">    <span class="comment">// 1. 加载ConfigManager和MessageStore</span></span><br><span class="line">    <span class="keyword">boolean</span> result = <span class="keyword">this</span>.topicConfigManager.load();</span><br><span class="line">    result = result &amp;&amp; <span class="keyword">this</span>.consumerOffsetManager.load();</span><br><span class="line">    result = result &amp;&amp; <span class="keyword">this</span>.subscriptionGroupManager.load();</span><br><span class="line">    result = result &amp;&amp; <span class="keyword">this</span>.consumerFilterManager.load();</span><br><span class="line">    <span class="keyword">if</span> (result) &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">this</span>.messageStore =</span><br><span class="line">                <span class="keyword">new</span> DefaultMessageStore(<span class="keyword">this</span>.messageStoreConfig, <span class="keyword">this</span>.brokerStatsManager, <span class="keyword">this</span>.messageArrivingListener,</span><br><span class="line">                    <span class="keyword">this</span>.brokerConfig);</span><br><span class="line">            <span class="keyword">this</span>.brokerStats = <span class="keyword">new</span> BrokerStats((DefaultMessageStore) <span class="keyword">this</span>.messageStore);</span><br><span class="line">            <span class="comment">//load plugin</span></span><br><span class="line">            MessageStorePluginContext context = <span class="keyword">new</span> MessageStorePluginContext(messageStoreConfig, brokerStatsManager, messageArrivingListener, brokerConfig);</span><br><span class="line">            <span class="keyword">this</span>.messageStore = MessageStoreFactory.build(context, <span class="keyword">this</span>.messageStore);</span><br><span class="line">            <span class="keyword">this</span>.messageStore.getDispatcherList().addFirst(<span class="keyword">new</span> CommitLogDispatcherCalcBitMap(<span class="keyword">this</span>.brokerConfig, <span class="keyword">this</span>.consumerFilterManager));</span><br><span class="line">        &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">            result = <span class="keyword">false</span>;</span><br><span class="line">            log.error(<span class="string">"Failed to initialize"</span>, e);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    result = result &amp;&amp; <span class="keyword">this</span>.messageStore.load();</span><br><span class="line">    <span class="comment">// 2. 初始化NettyRemotingServer</span></span><br><span class="line">    <span class="comment">// 3. 初始化线程池</span></span><br><span class="line">    <span class="comment">// 4. 为NettyRemotingServer注册处理器</span></span><br><span class="line">    <span class="comment">// 5. 开启定时任务</span></span><br><span class="line">    <span class="comment">// 6. tls模式的文件监听</span></span><br><span class="line">    <span class="comment">// 7. 初始化事务线程</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<ol>
<li><strong>TopicConfigManager</strong> Topic配置管理，比如每个Topic的读写队列数量。</li>
<li><strong>ConsumerOffsetManager</strong> 消费者进度管理</li>
<li><strong>SubscriptionGroupManager</strong> 订阅管理</li>
<li><strong>ConsumerFilterManager</strong> 消费者过滤管理 </li>
<li><strong>MessageStore</strong> 消息存储管理</li>
</ol>
<p>几个管理器内部的代码在此不再深究，看一下第二部分初始化NettyRemotingServer的代码：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">initialize</span><span class="params">()</span> <span class="keyword">throws</span> CloneNotSupportedException </span>&#123;</span><br><span class="line">    <span class="comment">// 1. 加载ConfigManager和MessageStore</span></span><br><span class="line">    <span class="comment">// 2. 初始化NettyRemotingServer</span></span><br><span class="line">    <span class="keyword">if</span> (result) &#123;</span><br><span class="line">        <span class="keyword">this</span>.remotingServer = <span class="keyword">new</span> NettyRemotingServer(<span class="keyword">this</span>.nettyServerConfig, <span class="keyword">this</span>.clientHousekeepingService);</span><br><span class="line">        NettyServerConfig fastConfig = (NettyServerConfig) <span class="keyword">this</span>.nettyServerConfig.clone();</span><br><span class="line">        fastConfig.setListenPort(nettyServerConfig.getListenPort() - <span class="number">2</span>);</span><br><span class="line">        <span class="keyword">this</span>.fastRemotingServer = <span class="keyword">new</span> NettyRemotingServer(fastConfig, <span class="keyword">this</span>.clientHousekeepingService);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 3. 初始化线程池</span></span><br><span class="line">    <span class="comment">// 4. 为NettyRemotingServer注册处理器</span></span><br><span class="line">    <span class="comment">// 5. 开启定时任务</span></span><br><span class="line">    <span class="comment">// 6. tls模式的文件监听</span></span><br><span class="line">    <span class="comment">// 7. 初始化事务线程</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>注意这里初始化了两个NettyRemotingServer，他们除了listener port不一样，其余的配置都相同。那么为什么要初始化两个配置一样的NettyRemotingServer？其实remotingServer是正统的消息处理通道，而fastRemotingServer则是负责主从同步，两者功能上的差异可以从后面各自注册的处理器可以看出来。</p>
<p>继续看第三部分代码初始化线程池：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">initialize</span><span class="params">()</span> <span class="keyword">throws</span> CloneNotSupportedException </span>&#123;</span><br><span class="line">    <span class="comment">// 1. 加载ConfigManager和MessageStore</span></span><br><span class="line">    <span class="comment">// 2. 初始化NettyRemotingServer</span></span><br><span class="line">    <span class="comment">// 3. 初始化线程池</span></span><br><span class="line">    <span class="keyword">if</span> (result) &#123;</span><br><span class="line">        <span class="keyword">this</span>.sendMessageExecutor = <span class="keyword">new</span> BrokerFixedThreadPoolExecutor(</span><br><span class="line">            <span class="keyword">this</span>.brokerConfig.getSendMessageThreadPoolNums(),</span><br><span class="line">            <span class="keyword">this</span>.brokerConfig.getSendMessageThreadPoolNums(),</span><br><span class="line">            <span class="number">1000</span> * <span class="number">60</span>,</span><br><span class="line">            TimeUnit.MILLISECONDS,</span><br><span class="line">            <span class="keyword">this</span>.sendThreadPoolQueue,</span><br><span class="line">            <span class="keyword">new</span> ThreadFactoryImpl(<span class="string">"SendMessageThread_"</span>));</span><br><span class="line"></span><br><span class="line">        <span class="keyword">this</span>.pullMessageExecutor = <span class="keyword">new</span> BrokerFixedThreadPoolExecutor(</span><br><span class="line">            <span class="keyword">this</span>.brokerConfig.getPullMessageThreadPoolNums(),</span><br><span class="line">            <span class="keyword">this</span>.brokerConfig.getPullMessageThreadPoolNums(),</span><br><span class="line">            <span class="number">1000</span> * <span class="number">60</span>,</span><br><span class="line">            TimeUnit.MILLISECONDS,</span><br><span class="line">            <span class="keyword">this</span>.pullThreadPoolQueue,</span><br><span class="line">            <span class="keyword">new</span> ThreadFactoryImpl(<span class="string">"PullMessageThread_"</span>));</span><br><span class="line"></span><br><span class="line">        <span class="keyword">this</span>.queryMessageExecutor = <span class="keyword">new</span> BrokerFixedThreadPoolExecutor(</span><br><span class="line">            <span class="keyword">this</span>.brokerConfig.getQueryMessageThreadPoolNums(),</span><br><span class="line">            <span class="keyword">this</span>.brokerConfig.getQueryMessageThreadPoolNums(),</span><br><span class="line">            <span class="number">1000</span> * <span class="number">60</span>,</span><br><span class="line">            TimeUnit.MILLISECONDS,</span><br><span class="line">            <span class="keyword">this</span>.queryThreadPoolQueue,</span><br><span class="line">            <span class="keyword">new</span> ThreadFactoryImpl(<span class="string">"QueryMessageThread_"</span>));</span><br><span class="line"></span><br><span class="line">        <span class="keyword">this</span>.adminBrokerExecutor =</span><br><span class="line">            Executors.newFixedThreadPool(<span class="keyword">this</span>.brokerConfig.getAdminBrokerThreadPoolNums(), <span class="keyword">new</span> ThreadFactoryImpl(</span><br><span class="line">                <span class="string">"AdminBrokerThread_"</span>));</span><br><span class="line"></span><br><span class="line">        <span class="keyword">this</span>.clientManageExecutor = <span class="keyword">new</span> ThreadPoolExecutor(</span><br><span class="line">            <span class="keyword">this</span>.brokerConfig.getClientManageThreadPoolNums(),</span><br><span class="line">            <span class="keyword">this</span>.brokerConfig.getClientManageThreadPoolNums(),</span><br><span class="line">            <span class="number">1000</span> * <span class="number">60</span>,</span><br><span class="line">            TimeUnit.MILLISECONDS,</span><br><span class="line">            <span class="keyword">this</span>.clientManagerThreadPoolQueue,</span><br><span class="line">            <span class="keyword">new</span> ThreadFactoryImpl(<span class="string">"ClientManageThread_"</span>));</span><br><span class="line"></span><br><span class="line">        <span class="keyword">this</span>.heartbeatExecutor = <span class="keyword">new</span> BrokerFixedThreadPoolExecutor(</span><br><span class="line">            <span class="keyword">this</span>.brokerConfig.getHeartbeatThreadPoolNums(),</span><br><span class="line">            <span class="keyword">this</span>.brokerConfig.getHeartbeatThreadPoolNums(),</span><br><span class="line">            <span class="number">1000</span> * <span class="number">60</span>,</span><br><span class="line">            TimeUnit.MILLISECONDS,</span><br><span class="line">            <span class="keyword">this</span>.heartbeatThreadPoolQueue,</span><br><span class="line">            <span class="keyword">new</span> ThreadFactoryImpl(<span class="string">"HeartbeatThread_"</span>,<span class="keyword">true</span>));</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="keyword">this</span>.consumerManageExecutor =</span><br><span class="line">            Executors.newFixedThreadPool(<span class="keyword">this</span>.brokerConfig.getConsumerManageThreadPoolNums(), <span class="keyword">new</span> ThreadFactoryImpl(</span><br><span class="line">                <span class="string">"ConsumerManageThread_"</span>));</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 4. 为NettyRemotingServer注册处理器</span></span><br><span class="line">    <span class="comment">// 5. 开启定时任务</span></span><br><span class="line">    <span class="comment">// 6. tls模式的文件监听</span></span><br><span class="line">    <span class="comment">// 7. 初始化事务线程</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>从名字上就可以看出来几个线程池的作用了，所以不再赘述。继续看第四部为NettyRemotingServer注册处理器：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">initialize</span><span class="params">()</span> <span class="keyword">throws</span> CloneNotSupportedException </span>&#123;</span><br><span class="line">    <span class="comment">// 1. 加载ConfigManager和MessageStore</span></span><br><span class="line">    <span class="comment">// 2. 初始化NettyRemotingServer</span></span><br><span class="line">    <span class="comment">// 4. 为NettyRemotingServer注册处理器</span></span><br><span class="line">    <span class="keyword">if</span> (result) &#123;</span><br><span class="line">        <span class="keyword">this</span>.registerProcessor();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 5. 开启定时任务</span></span><br><span class="line">    <span class="comment">// 6. tls模式的文件监听</span></span><br><span class="line">    <span class="comment">// 7. 初始化事务线程</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>贴一下<strong>registerProcessor()</strong>的代码：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">registerProcessor</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">        * SendMessageProcessor</span></span><br><span class="line"><span class="comment">        */</span></span><br><span class="line">    SendMessageProcessor sendProcessor = <span class="keyword">new</span> SendMessageProcessor(<span class="keyword">this</span>);</span><br><span class="line">    sendProcessor.registerSendMessageHook(sendMessageHookList);</span><br><span class="line">    sendProcessor.registerConsumeMessageHook(consumeMessageHookList);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">this</span>.remotingServer.registerProcessor(RequestCode.SEND_MESSAGE, sendProcessor, <span class="keyword">this</span>.sendMessageExecutor);</span><br><span class="line">    <span class="keyword">this</span>.remotingServer.registerProcessor(RequestCode.SEND_MESSAGE_V2, sendProcessor, <span class="keyword">this</span>.sendMessageExecutor);</span><br><span class="line">    <span class="keyword">this</span>.remotingServer.registerProcessor(RequestCode.SEND_BATCH_MESSAGE, sendProcessor, <span class="keyword">this</span>.sendMessageExecutor);</span><br><span class="line">    <span class="keyword">this</span>.remotingServer.registerProcessor(RequestCode.CONSUMER_SEND_MSG_BACK, sendProcessor, <span class="keyword">this</span>.sendMessageExecutor);</span><br><span class="line">    <span class="keyword">this</span>.fastRemotingServer.registerProcessor(RequestCode.SEND_MESSAGE, sendProcessor, <span class="keyword">this</span>.sendMessageExecutor);</span><br><span class="line">    <span class="keyword">this</span>.fastRemotingServer.registerProcessor(RequestCode.SEND_MESSAGE_V2, sendProcessor, <span class="keyword">this</span>.sendMessageExecutor);</span><br><span class="line">    <span class="keyword">this</span>.fastRemotingServer.registerProcessor(RequestCode.SEND_BATCH_MESSAGE, sendProcessor, <span class="keyword">this</span>.sendMessageExecutor);</span><br><span class="line">    <span class="keyword">this</span>.fastRemotingServer.registerProcessor(RequestCode.CONSUMER_SEND_MSG_BACK, sendProcessor, <span class="keyword">this</span>.sendMessageExecutor);</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">        * PullMessageProcessor</span></span><br><span class="line"><span class="comment">        */</span></span><br><span class="line">    <span class="keyword">this</span>.remotingServer.registerProcessor(RequestCode.PULL_MESSAGE, <span class="keyword">this</span>.pullMessageProcessor, <span class="keyword">this</span>.pullMessageExecutor);</span><br><span class="line">    <span class="keyword">this</span>.pullMessageProcessor.registerConsumeMessageHook(consumeMessageHookList);</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">        * QueryMessageProcessor</span></span><br><span class="line"><span class="comment">        */</span></span><br><span class="line">    NettyRequestProcessor queryProcessor = <span class="keyword">new</span> QueryMessageProcessor(<span class="keyword">this</span>);</span><br><span class="line">    <span class="keyword">this</span>.remotingServer.registerProcessor(RequestCode.QUERY_MESSAGE, queryProcessor, <span class="keyword">this</span>.queryMessageExecutor);</span><br><span class="line">    <span class="keyword">this</span>.remotingServer.registerProcessor(RequestCode.VIEW_MESSAGE_BY_ID, queryProcessor, <span class="keyword">this</span>.queryMessageExecutor);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">this</span>.fastRemotingServer.registerProcessor(RequestCode.QUERY_MESSAGE, queryProcessor, <span class="keyword">this</span>.queryMessageExecutor);</span><br><span class="line">    <span class="keyword">this</span>.fastRemotingServer.registerProcessor(RequestCode.VIEW_MESSAGE_BY_ID, queryProcessor, <span class="keyword">this</span>.queryMessageExecutor);</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">        * ClientManageProcessor</span></span><br><span class="line"><span class="comment">        */</span></span><br><span class="line">    ClientManageProcessor clientProcessor = <span class="keyword">new</span> ClientManageProcessor(<span class="keyword">this</span>);</span><br><span class="line">    <span class="keyword">this</span>.remotingServer.registerProcessor(RequestCode.HEART_BEAT, clientProcessor, <span class="keyword">this</span>.heartbeatExecutor);</span><br><span class="line">    <span class="keyword">this</span>.remotingServer.registerProcessor(RequestCode.UNREGISTER_CLIENT, clientProcessor, <span class="keyword">this</span>.clientManageExecutor);</span><br><span class="line">    <span class="keyword">this</span>.remotingServer.registerProcessor(RequestCode.CHECK_CLIENT_CONFIG, clientProcessor, <span class="keyword">this</span>.clientManageExecutor);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">this</span>.fastRemotingServer.registerProcessor(RequestCode.HEART_BEAT, clientProcessor, <span class="keyword">this</span>.heartbeatExecutor);</span><br><span class="line">    <span class="keyword">this</span>.fastRemotingServer.registerProcessor(RequestCode.UNREGISTER_CLIENT, clientProcessor, <span class="keyword">this</span>.clientManageExecutor);</span><br><span class="line">    <span class="keyword">this</span>.fastRemotingServer.registerProcessor(RequestCode.CHECK_CLIENT_CONFIG, clientProcessor, <span class="keyword">this</span>.clientManageExecutor);</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">        * ConsumerManageProcessor</span></span><br><span class="line"><span class="comment">        */</span></span><br><span class="line">    ConsumerManageProcessor consumerManageProcessor = <span class="keyword">new</span> ConsumerManageProcessor(<span class="keyword">this</span>);</span><br><span class="line">    <span class="keyword">this</span>.remotingServer.registerProcessor(RequestCode.GET_CONSUMER_LIST_BY_GROUP, consumerManageProcessor, <span class="keyword">this</span>.consumerManageExecutor);</span><br><span class="line">    <span class="keyword">this</span>.remotingServer.registerProcessor(RequestCode.UPDATE_CONSUMER_OFFSET, consumerManageProcessor, <span class="keyword">this</span>.consumerManageExecutor);</span><br><span class="line">    <span class="keyword">this</span>.remotingServer.registerProcessor(RequestCode.QUERY_CONSUMER_OFFSET, consumerManageProcessor, <span class="keyword">this</span>.consumerManageExecutor);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">this</span>.fastRemotingServer.registerProcessor(RequestCode.GET_CONSUMER_LIST_BY_GROUP, consumerManageProcessor, <span class="keyword">this</span>.consumerManageExecutor);</span><br><span class="line">    <span class="keyword">this</span>.fastRemotingServer.registerProcessor(RequestCode.UPDATE_CONSUMER_OFFSET, consumerManageProcessor, <span class="keyword">this</span>.consumerManageExecutor);</span><br><span class="line">    <span class="keyword">this</span>.fastRemotingServer.registerProcessor(RequestCode.QUERY_CONSUMER_OFFSET, consumerManageProcessor, <span class="keyword">this</span>.consumerManageExecutor);</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">        * EndTransactionProcessor</span></span><br><span class="line"><span class="comment">        */</span></span><br><span class="line">    <span class="keyword">this</span>.remotingServer.registerProcessor(RequestCode.END_TRANSACTION, <span class="keyword">new</span> EndTransactionProcessor(<span class="keyword">this</span>), <span class="keyword">this</span>.sendMessageExecutor);</span><br><span class="line">    <span class="keyword">this</span>.fastRemotingServer.registerProcessor(RequestCode.END_TRANSACTION, <span class="keyword">new</span> EndTransactionProcessor(<span class="keyword">this</span>), <span class="keyword">this</span>.sendMessageExecutor);</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">        * Default</span></span><br><span class="line"><span class="comment">        */</span></span><br><span class="line">    AdminBrokerProcessor adminProcessor = <span class="keyword">new</span> AdminBrokerProcessor(<span class="keyword">this</span>);</span><br><span class="line">    <span class="keyword">this</span>.remotingServer.registerDefaultProcessor(adminProcessor, <span class="keyword">this</span>.adminBrokerExecutor);</span><br><span class="line">    <span class="keyword">this</span>.fastRemotingServer.registerDefaultProcessor(adminProcessor, <span class="keyword">this</span>.adminBrokerExecutor);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>主要是为remotingServer和fastRemotingServer注册处理器，几个处理器的分类已经标的很清楚。这里remotingServer和fastRemotingServer注册的处理器大致相同，只有<strong>PullMessageProcessor</strong>这个处理器不同，只有remotingServer注册了，fastRemotingServer并没有注册。</p>
<p>几个Processor先不做深入探讨，继续看第五部分代码开启定时任务：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">initialize</span><span class="params">()</span> <span class="keyword">throws</span> CloneNotSupportedException </span>&#123;</span><br><span class="line">    <span class="comment">// 1. 加载ConfigManager和MessageStore</span></span><br><span class="line">    <span class="comment">// 2. 初始化NettyRemotingServer</span></span><br><span class="line">    <span class="comment">// 4. 为NettyRemotingServer注册处理器</span></span><br><span class="line">    <span class="comment">// 5. 开启定时任务</span></span><br><span class="line">    <span class="keyword">if</span> (result) &#123;</span><br><span class="line">        <span class="keyword">final</span> <span class="keyword">long</span> initialDelay = UtilAll.computNextMorningTimeMillis() - System.currentTimeMillis();</span><br><span class="line">                <span class="keyword">final</span> <span class="keyword">long</span> period = <span class="number">1000</span> * <span class="number">60</span> * <span class="number">60</span> * <span class="number">24</span>;</span><br><span class="line">                <span class="comment">// 1. 每天记录消息获取、存储的数量。</span></span><br><span class="line">                <span class="keyword">this</span>.scheduledExecutorService.scheduleAtFixedRate(<span class="keyword">new</span> Runnable() &#123;</span><br><span class="line">                    <span class="meta">@Override</span></span><br><span class="line">                    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">                        <span class="keyword">try</span> &#123;</span><br><span class="line">                            BrokerController.<span class="keyword">this</span>.getBrokerStats().record();</span><br><span class="line">                        &#125; <span class="keyword">catch</span> (Throwable e) &#123;</span><br><span class="line">                            log.error(<span class="string">"schedule record error."</span>, e);</span><br><span class="line">                        &#125;</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;, initialDelay, period, TimeUnit.MILLISECONDS);</span><br><span class="line">                <span class="comment">// 2. 每隔5秒序列化存储ConsumerOffsetManager</span></span><br><span class="line">                <span class="keyword">this</span>.scheduledExecutorService.scheduleAtFixedRate(<span class="keyword">new</span> Runnable() &#123;</span><br><span class="line">                    <span class="meta">@Override</span></span><br><span class="line">                    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">                        <span class="keyword">try</span> &#123;</span><br><span class="line">                            BrokerController.<span class="keyword">this</span>.consumerOffsetManager.persist();</span><br><span class="line">                        &#125; <span class="keyword">catch</span> (Throwable e) &#123;</span><br><span class="line">                            log.error(<span class="string">"schedule persist consumerOffset error."</span>, e);</span><br><span class="line">                        &#125;</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;, <span class="number">1000</span> * <span class="number">10</span>, <span class="keyword">this</span>.brokerConfig.getFlushConsumerOffsetInterval(), TimeUnit.MILLISECONDS);</span><br><span class="line">                <span class="comment">// 3. 每隔10秒序列化存储ConsumerFilterManager</span></span><br><span class="line">                <span class="keyword">this</span>.scheduledExecutorService.scheduleAtFixedRate(<span class="keyword">new</span> Runnable() &#123;</span><br><span class="line">                    <span class="meta">@Override</span></span><br><span class="line">                    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">                        <span class="keyword">try</span> &#123;</span><br><span class="line">                            BrokerController.<span class="keyword">this</span>.consumerFilterManager.persist();</span><br><span class="line">                        &#125; <span class="keyword">catch</span> (Throwable e) &#123;</span><br><span class="line">                            log.error(<span class="string">"schedule persist consumer filter error."</span>, e);</span><br><span class="line">                        &#125;</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;, <span class="number">1000</span> * <span class="number">10</span>, <span class="number">1000</span> * <span class="number">10</span>, TimeUnit.MILLISECONDS);</span><br><span class="line"></span><br><span class="line">                <span class="keyword">this</span>.scheduledExecutorService.scheduleAtFixedRate(<span class="keyword">new</span> Runnable() &#123;</span><br><span class="line">                    <span class="meta">@Override</span></span><br><span class="line">                    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">                        <span class="keyword">try</span> &#123;</span><br><span class="line">                            <span class="comment">// 4. 每隔3分钟检测并清理消费失败消息累计达到阈值（consumerFallbehindThreshold）的消费者</span></span><br><span class="line">                            BrokerController.<span class="keyword">this</span>.protectBroker();</span><br><span class="line">                        &#125; <span class="keyword">catch</span> (Throwable e) &#123;</span><br><span class="line">                            log.error(<span class="string">"protectBroker error."</span>, e);</span><br><span class="line">                        &#125;</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;, <span class="number">3</span>, <span class="number">3</span>, TimeUnit.MINUTES);</span><br><span class="line"></span><br><span class="line">                <span class="keyword">this</span>.scheduledExecutorService.scheduleAtFixedRate(<span class="keyword">new</span> Runnable() &#123;</span><br><span class="line">                    <span class="meta">@Override</span></span><br><span class="line">                    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">                        <span class="keyword">try</span> &#123;</span><br><span class="line">                            BrokerController.<span class="keyword">this</span>.printWaterMark();</span><br><span class="line">                        &#125; <span class="keyword">catch</span> (Throwable e) &#123;</span><br><span class="line">                            log.error(<span class="string">"printWaterMark error."</span>, e);</span><br><span class="line">                        &#125;</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;, <span class="number">10</span>, <span class="number">1</span>, TimeUnit.SECONDS);</span><br><span class="line"></span><br><span class="line">                <span class="keyword">this</span>.scheduledExecutorService.scheduleAtFixedRate(<span class="keyword">new</span> Runnable() &#123;</span><br><span class="line"></span><br><span class="line">                    <span class="meta">@Override</span></span><br><span class="line">                    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">                        <span class="keyword">try</span> &#123;</span><br><span class="line">                            log.info(<span class="string">"dispatch behind commit log &#123;&#125; bytes"</span>, BrokerController.<span class="keyword">this</span>.getMessageStore().dispatchBehindBytes());</span><br><span class="line">                        &#125; <span class="keyword">catch</span> (Throwable e) &#123;</span><br><span class="line">                            log.error(<span class="string">"schedule dispatchBehindBytes error."</span>, e);</span><br><span class="line">                        &#125;</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;, <span class="number">1000</span> * <span class="number">10</span>, <span class="number">1000</span> * <span class="number">60</span>, TimeUnit.MILLISECONDS);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 6. tls模式的文件监听</span></span><br><span class="line">    <span class="comment">// 7. 初始化事务线程</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<ol>
<li>每天记录消息获取、存储的数量。</li>
<li>每隔5秒序列化存储ConsumerOffsetManager</li>
<li>每隔10秒序列化存储ConsumerFilterManager</li>
<li>每隔3分钟检测并清理消费失败消息累计达到阈值（consumerFallbehindThreshold）的消费者</li>
<li>每隔1秒打印生产队列、消费队列、查询队列的信息。查看头队列节点任务的创建时间，可以查看任务的延迟完成时间。</li>
<li>每隔1分钟打印已经持久化但是未发送给消费者的消息容量</li>
<li>如果<strong>BrokerConfig</strong>未配置namesrvAddr，且配置fetchNamesrvAddrByAddressServer为true，则启动定时任务使用系统默认的namesrvAddr每隔两分钟拉取namesrvAddr。</li>
<li><p>如果Broker为Slave，启动一个定时任务每隔1分钟与Master同步信息：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">syncAll</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 同步Topic配置</span></span><br><span class="line">    <span class="keyword">this</span>.syncTopicConfig();</span><br><span class="line">    <span class="comment">// 同步消费进度</span></span><br><span class="line">    <span class="keyword">this</span>.syncConsumerOffset();</span><br><span class="line">    <span class="comment">// 同步延迟消费进度</span></span><br><span class="line">    <span class="keyword">this</span>.syncDelayOffset();</span><br><span class="line">    <span class="comment">// 同步订阅配置</span></span><br><span class="line">    <span class="keyword">this</span>.syncSubscriptionGroupConfig();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>如果Broker是Master，启动定时任务每隔一分钟打印Store中Slave落后Master的字节数</p>
</li>
</ol>
<p>继续看第六部分代码：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">initialize</span><span class="params">()</span> <span class="keyword">throws</span> CloneNotSupportedException </span>&#123;</span><br><span class="line">    <span class="comment">// 1. 加载ConfigManager和MessageStore</span></span><br><span class="line">    <span class="comment">// 2. 初始化NettyRemotingServer</span></span><br><span class="line">    <span class="comment">// 4. 为NettyRemotingServer注册处理器</span></span><br><span class="line">    <span class="comment">// 5. 开启定时任务</span></span><br><span class="line">    <span class="comment">// 6. tls模式的文件监听</span></span><br><span class="line">    <span class="keyword">if</span> (result) &#123;</span><br><span class="line">        <span class="keyword">if</span> (TlsSystemConfig.tlsMode != TlsMode.DISABLED) &#123;</span><br><span class="line">                <span class="comment">// Register a listener to reload SslContext</span></span><br><span class="line">                <span class="keyword">try</span> &#123;</span><br><span class="line">                    fileWatchService = <span class="keyword">new</span> FileWatchService(</span><br><span class="line">                        <span class="keyword">new</span> String[] &#123;</span><br><span class="line">                            TlsSystemConfig.tlsServerCertPath,</span><br><span class="line">                            TlsSystemConfig.tlsServerKeyPath,</span><br><span class="line">                            TlsSystemConfig.tlsServerTrustCertPath</span><br><span class="line">                        &#125;,</span><br><span class="line">                        <span class="keyword">new</span> FileWatchService.Listener() &#123;</span><br><span class="line">                            <span class="keyword">boolean</span> certChanged, keyChanged = <span class="keyword">false</span>;</span><br><span class="line"></span><br><span class="line">                            <span class="meta">@Override</span></span><br><span class="line">                            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onChanged</span><span class="params">(String path)</span> </span>&#123;</span><br><span class="line">                                <span class="keyword">if</span> (path.equals(TlsSystemConfig.tlsServerTrustCertPath)) &#123;</span><br><span class="line">                                    log.info(<span class="string">"The trust certificate changed, reload the ssl context"</span>);</span><br><span class="line">                                    reloadServerSslContext();</span><br><span class="line">                                &#125;</span><br><span class="line">                                <span class="keyword">if</span> (path.equals(TlsSystemConfig.tlsServerCertPath)) &#123;</span><br><span class="line">                                    certChanged = <span class="keyword">true</span>;</span><br><span class="line">                                &#125;</span><br><span class="line">                                <span class="keyword">if</span> (path.equals(TlsSystemConfig.tlsServerKeyPath)) &#123;</span><br><span class="line">                                    keyChanged = <span class="keyword">true</span>;</span><br><span class="line">                                &#125;</span><br><span class="line">                                <span class="keyword">if</span> (certChanged &amp;&amp; keyChanged) &#123;</span><br><span class="line">                                    log.info(<span class="string">"The certificate and private key changed, reload the ssl context"</span>);</span><br><span class="line">                                    certChanged = keyChanged = <span class="keyword">false</span>;</span><br><span class="line">                                    reloadServerSslContext();</span><br><span class="line">                                &#125;</span><br><span class="line">                            &#125;</span><br><span class="line"></span><br><span class="line">                            <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">reloadServerSslContext</span><span class="params">()</span> </span>&#123;</span><br><span class="line">                                ((NettyRemotingServer) remotingServer).loadSslContext();</span><br><span class="line">                                ((NettyRemotingServer) fastRemotingServer).loadSslContext();</span><br><span class="line">                            &#125;</span><br><span class="line">                        &#125;);</span><br><span class="line">                &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">                    log.warn(<span class="string">"FileWatchService created error, can't load the certificate dynamically"</span>);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 7. 初始化事务线程</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>tls模式下，监听tls证书是否发生改变，如果改变则立即重新加载tls上下文。最后，第七部分是初始化事务：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">initialize</span><span class="params">()</span> <span class="keyword">throws</span> CloneNotSupportedException </span>&#123;</span><br><span class="line">    <span class="comment">// 1. 加载ConfigManager和MessageStore</span></span><br><span class="line">    <span class="comment">// 2. 初始化NettyRemotingServer</span></span><br><span class="line">    <span class="comment">// 4. 为NettyRemotingServer注册处理器</span></span><br><span class="line">    <span class="comment">// 5. 开启定时任务</span></span><br><span class="line">    <span class="comment">// 6. tls模式的文件监听</span></span><br><span class="line">    <span class="comment">// 7. 初始化事务线程</span></span><br><span class="line">    <span class="keyword">if</span> (result) &#123;</span><br><span class="line">        initialTransaction();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> result;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>事务部分后续再另开模块探讨。</p>
<h4 id="启动"><a href="#启动" class="headerlink" title="启动"></a>启动</h4><p>直接看一下<strong>BrokerController</strong>的<strong>start()</strong>：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">start</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.messageStore != <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">this</span>.messageStore.start();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.remotingServer != <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">this</span>.remotingServer.start();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.fastRemotingServer != <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">this</span>.fastRemotingServer.start();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.fileWatchService != <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">this</span>.fileWatchService.start();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.brokerOuterAPI != <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">this</span>.brokerOuterAPI.start();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.pullRequestHoldService != <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">this</span>.pullRequestHoldService.start();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.clientHousekeepingService != <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">this</span>.clientHousekeepingService.start();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.filterServerManager != <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">this</span>.filterServerManager.start();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">this</span>.registerBrokerAll(<span class="keyword">true</span>, <span class="keyword">false</span>, <span class="keyword">true</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">this</span>.scheduledExecutorService.scheduleAtFixedRate(<span class="keyword">new</span> Runnable() &#123;</span><br><span class="line"></span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                BrokerController.<span class="keyword">this</span>.registerBrokerAll(<span class="keyword">true</span>, <span class="keyword">false</span>, brokerConfig.isForceRegister());</span><br><span class="line">            &#125; <span class="keyword">catch</span> (Throwable e) &#123;</span><br><span class="line">                log.error(<span class="string">"registerBrokerAll Exception"</span>, e);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;, <span class="number">1000</span> * <span class="number">10</span>, Math.max(<span class="number">10000</span>, Math.min(brokerConfig.getRegisterNameServerPeriod(), <span class="number">60000</span>)), TimeUnit.MILLISECONDS);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.brokerStatsManager != <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">this</span>.brokerStatsManager.start();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.brokerFastFailure != <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">this</span>.brokerFastFailure.start();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (BrokerRole.SLAVE != messageStoreConfig.getBrokerRole()) &#123;</span><br><span class="line">        <span class="keyword">if</span> (<span class="keyword">this</span>.transactionalMessageCheckService != <span class="keyword">null</span>) &#123;</span><br><span class="line">            log.info(<span class="string">"Start transaction service!"</span>);</span><br><span class="line">            <span class="keyword">this</span>.transactionalMessageCheckService.start();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<ol>
<li><strong>MessageStore</strong> 属于store模块，应该是消息持久化相关，后面再讨论。</li>
<li>remotingServer和fastRemotingServer 同属于<strong>RemotingServer</strong>都是remoting模块中的netty服务端，两者所有的处理行为都保持一致，只是监听的端口不同。</li>
<li><strong>FileWatchService</strong> 文件监听，namesrv模块也曾遇到。</li>
<li><strong>BrokerOuterAPI</strong> 对外调用的api封装</li>
<li><strong>PullRequestHoldService</strong> 继承自ServiceThread，是一个服务线程。当拉取消息的请求获取不到消息的时候，此线程会挂起这个请求，直至有消息或者挂起超时。</li>
<li><strong>ClientHousekeepingService</strong>继承自ChannelEventListener，作为一个网络通道监听器。<strong>ClientHousekeepingService</strong>内部还有一个定时器，定时清理关闭通道的消息。</li>
<li><strong>FilterServerManager</strong> 过滤服务管理，30秒一次定时检查Filter Server个数，调用shell命令创建。</li>
<li><strong>registerBrokerAll()</strong> 注册Broker。</li>
<li><strong>BrokerStatsManager</strong> 记录管理broker的状态。</li>
<li><strong>BrokerFastFailure</strong> 每隔10ms检测系统页缓存是否繁忙，如果是的话执行流控制迅速给客户端返回失败。</li>
<li><strong>TransactionalMessageCheckService</strong> 如果是master，开启事务检测线程。</li>
</ol>
<h4 id="namesrv注册"><a href="#namesrv注册" class="headerlink" title="namesrv注册"></a>namesrv注册</h4><p>&emsp;&emsp;来看下<strong>registerBrokerAll()</strong>的代码：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">synchronized</span> <span class="keyword">void</span> <span class="title">registerBrokerAll</span><span class="params">(<span class="keyword">final</span> <span class="keyword">boolean</span> checkOrderConfig, <span class="keyword">boolean</span> oneway, <span class="keyword">boolean</span> forceRegister)</span> </span>&#123;</span><br><span class="line">    TopicConfigSerializeWrapper topicConfigWrapper = <span class="keyword">this</span>.getTopicConfigManager().buildTopicConfigSerializeWrapper();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (!PermName.isWriteable(<span class="keyword">this</span>.getBrokerConfig().getBrokerPermission())</span><br><span class="line">        || !PermName.isReadable(<span class="keyword">this</span>.getBrokerConfig().getBrokerPermission())) &#123;</span><br><span class="line">        ConcurrentHashMap&lt;String, TopicConfig&gt; topicConfigTable = <span class="keyword">new</span> ConcurrentHashMap&lt;String, TopicConfig&gt;();</span><br><span class="line">        <span class="keyword">for</span> (TopicConfig topicConfig : topicConfigWrapper.getTopicConfigTable().values()) &#123;</span><br><span class="line">            TopicConfig tmp =</span><br><span class="line">                <span class="keyword">new</span> TopicConfig(topicConfig.getTopicName(), topicConfig.getReadQueueNums(), topicConfig.getWriteQueueNums(),</span><br><span class="line">                    <span class="keyword">this</span>.brokerConfig.getBrokerPermission());</span><br><span class="line">            topicConfigTable.put(topicConfig.getTopicName(), tmp);</span><br><span class="line">        &#125;</span><br><span class="line">        topicConfigWrapper.setTopicConfigTable(topicConfigTable);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (forceRegister || needRegister(<span class="keyword">this</span>.brokerConfig.getBrokerClusterName(),</span><br><span class="line">        <span class="keyword">this</span>.getBrokerAddr(),</span><br><span class="line">        <span class="keyword">this</span>.brokerConfig.getBrokerName(),</span><br><span class="line">        <span class="keyword">this</span>.brokerConfig.getBrokerId(),</span><br><span class="line">        <span class="keyword">this</span>.brokerConfig.getRegisterBrokerTimeoutMills())) &#123;</span><br><span class="line">        doRegisterBrokerAll(checkOrderConfig, oneway, topicConfigWrapper);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p><strong>TopicConfigManager</strong>会创建一些默认的topic，并缓存其配置。这里主要是拷贝一份topic配置集合<strong>topicConfigTable</strong>（ConcurrentMap&lt;String, TopicConfig&gt;）赋给TopicConfigSerializeWrapper，并传递给<strong>doRegisterBrokerAll()</strong>：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">doRegisterBrokerAll</span><span class="params">(<span class="keyword">boolean</span> checkOrderConfig, <span class="keyword">boolean</span> oneway,</span></span></span><br><span class="line"><span class="function"><span class="params">    TopicConfigSerializeWrapper topicConfigWrapper)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 1. 调用brokerOuterAPI注册</span></span><br><span class="line">    List&lt;RegisterBrokerResult&gt; registerBrokerResultList = <span class="keyword">this</span>.brokerOuterAPI.registerBrokerAll(</span><br><span class="line">        <span class="keyword">this</span>.brokerConfig.getBrokerClusterName(),</span><br><span class="line">        <span class="keyword">this</span>.getBrokerAddr(),</span><br><span class="line">        <span class="keyword">this</span>.brokerConfig.getBrokerName(),</span><br><span class="line">        <span class="keyword">this</span>.brokerConfig.getBrokerId(),</span><br><span class="line">        <span class="keyword">this</span>.getHAServerAddr(),</span><br><span class="line">        topicConfigWrapper,</span><br><span class="line">        <span class="keyword">this</span>.filterServerManager.buildNewFilterServerList(),</span><br><span class="line">        oneway,</span><br><span class="line">        <span class="keyword">this</span>.brokerConfig.getRegisterBrokerTimeoutMills(),</span><br><span class="line">        <span class="keyword">this</span>.brokerConfig.isCompressedRegister());</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 2. 注册成功返回（省略）</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>先看下前半部分调用<strong>BrokerOuterAPI</strong>中<strong>registerBrokerAll()</strong>的逻辑<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> List&lt;RegisterBrokerResult&gt; <span class="title">registerBrokerAll</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">    <span class="keyword">final</span> String clusterName,</span></span></span><br><span class="line"><span class="function"><span class="params">    <span class="keyword">final</span> String brokerAddr,</span></span></span><br><span class="line"><span class="function"><span class="params">    <span class="keyword">final</span> String brokerName,</span></span></span><br><span class="line"><span class="function"><span class="params">    <span class="keyword">final</span> <span class="keyword">long</span> brokerId,</span></span></span><br><span class="line"><span class="function"><span class="params">    <span class="keyword">final</span> String haServerAddr,</span></span></span><br><span class="line"><span class="function"><span class="params">    <span class="keyword">final</span> TopicConfigSerializeWrapper topicConfigWrapper,</span></span></span><br><span class="line"><span class="function"><span class="params">    <span class="keyword">final</span> List&lt;String&gt; filterServerList,</span></span></span><br><span class="line"><span class="function"><span class="params">    <span class="keyword">final</span> <span class="keyword">boolean</span> oneway,</span></span></span><br><span class="line"><span class="function"><span class="params">    <span class="keyword">final</span> <span class="keyword">int</span> timeoutMills,</span></span></span><br><span class="line"><span class="function"><span class="params">    <span class="keyword">final</span> <span class="keyword">boolean</span> compressed)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">final</span> List&lt;RegisterBrokerResult&gt; registerBrokerResultList = Lists.newArrayList();</span><br><span class="line">    List&lt;String&gt; nameServerAddressList = <span class="keyword">this</span>.remotingClient.getNameServerAddressList();</span><br><span class="line">    <span class="keyword">if</span> (nameServerAddressList != <span class="keyword">null</span> &amp;&amp; nameServerAddressList.size() &gt; <span class="number">0</span>) &#123;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">final</span> RegisterBrokerRequestHeader requestHeader = <span class="keyword">new</span> RegisterBrokerRequestHeader();</span><br><span class="line">        requestHeader.setBrokerAddr(brokerAddr);</span><br><span class="line">        requestHeader.setBrokerId(brokerId);</span><br><span class="line">        requestHeader.setBrokerName(brokerName);</span><br><span class="line">        requestHeader.setClusterName(clusterName);</span><br><span class="line">        requestHeader.setHaServerAddr(haServerAddr);</span><br><span class="line">        requestHeader.setCompressed(compressed);</span><br><span class="line"></span><br><span class="line">        RegisterBrokerBody requestBody = <span class="keyword">new</span> RegisterBrokerBody();</span><br><span class="line">        requestBody.setTopicConfigSerializeWrapper(topicConfigWrapper);</span><br><span class="line">        requestBody.setFilterServerList(filterServerList);</span><br><span class="line">        <span class="keyword">final</span> <span class="keyword">byte</span>[] body = requestBody.encode(compressed);</span><br><span class="line">        <span class="keyword">final</span> <span class="keyword">int</span> bodyCrc32 = UtilAll.crc32(body);</span><br><span class="line">        requestHeader.setBodyCrc32(bodyCrc32);</span><br><span class="line">        <span class="keyword">final</span> CountDownLatch countDownLatch = <span class="keyword">new</span> CountDownLatch(nameServerAddressList.size());</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">final</span> String namesrvAddr : nameServerAddressList) &#123;</span><br><span class="line">            brokerOuterExecutor.execute(<span class="keyword">new</span> Runnable() &#123;</span><br><span class="line">                <span class="meta">@Override</span></span><br><span class="line">                <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">                    <span class="keyword">try</span> &#123;</span><br><span class="line">                        RegisterBrokerResult result = registerBroker(namesrvAddr,oneway, timeoutMills,requestHeader,body);</span><br><span class="line">                        <span class="keyword">if</span> (result != <span class="keyword">null</span>) &#123;</span><br><span class="line">                            registerBrokerResultList.add(result);</span><br><span class="line">                        &#125;</span><br><span class="line"></span><br><span class="line">                        log.info(<span class="string">"register broker to name server &#123;&#125; OK"</span>, namesrvAddr);</span><br><span class="line">                    &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">                        log.warn(<span class="string">"registerBroker Exception, &#123;&#125;"</span>, namesrvAddr, e);</span><br><span class="line">                    &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">                        countDownLatch.countDown();</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            countDownLatch.await(timeoutMills, TimeUnit.MILLISECONDS);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> registerBrokerResultList;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>nameServerAddressList在initialize阶段就已经拉取并缓存了，这里遍历nameServerAddressList异步向各个nameServer注册Broker，此处使用CountDownLatch挂起主线程，直到注册请求返回结果。调用<strong>BrokerOuterAPI</strong>的<strong>registerBrokerAll()</strong>向name server注册的逻辑就此完毕，name server如何处理请求具体参照R<strong>ocketMQ之旅（二）namesrv</strong>。回过头继续看<strong>BrokerController</strong>的<strong>doRegisterBrokerAll()</strong>方法，注册完毕之后做了什么：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">doRegisterBrokerAll</span><span class="params">(<span class="keyword">boolean</span> checkOrderConfig, <span class="keyword">boolean</span> oneway,</span></span></span><br><span class="line"><span class="function"><span class="params">    TopicConfigSerializeWrapper topicConfigWrapper)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 1. 调用brokerOuterAPI注册（省略此处代码，上面已经贴了）</span></span><br><span class="line">    <span class="comment">// 2. 注册成功返回</span></span><br><span class="line">    <span class="keyword">if</span> (registerBrokerResultList.size() &gt; <span class="number">0</span>) &#123;</span><br><span class="line">        RegisterBrokerResult registerBrokerResult = registerBrokerResultList.get(<span class="number">0</span>);</span><br><span class="line">        <span class="keyword">if</span> (registerBrokerResult != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">if</span> (<span class="keyword">this</span>.updateMasterHAServerAddrPeriodically &amp;&amp; registerBrokerResult.getHaServerAddr() != <span class="keyword">null</span>) &#123;</span><br><span class="line">                <span class="keyword">this</span>.messageStore.updateHaMasterAddress(registerBrokerResult.getHaServerAddr());</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">this</span>.slaveSynchronize.setMasterAddr(registerBrokerResult.getMasterAddr());</span><br><span class="line"></span><br><span class="line">            <span class="keyword">if</span> (checkOrderConfig) &#123;</span><br><span class="line">                <span class="keyword">this</span>.getTopicConfigManager().updateOrderTopicConfig(registerBrokerResult.getKvTable());</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p><strong>updateMasterHAServerAddrPeriodically</strong>只有在master上才会设置为true，更新messageStore和slaveSynchronize的ha地址。这里registerBrokerResult.getKvTable()返回有序的topic列表，使用它来更新<strong>TopicConfigManager</strong>的topicConfigTable（ConcurrentMap&lt;String, TopicConfig&gt;），确保topic的有序性。</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/RocketMQ之旅/" rel="tag"># RocketMQ之旅</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/11/19/RocketMQ之旅（五）remoting/" rel="next" title="RocketMQ之旅（五）remoting">
                <i class="fa fa-chevron-left"></i> RocketMQ之旅（五）remoting
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/12/17/算法国（二）字符串匹配/" rel="prev" title="算法国（二）字符串匹配">
                算法国（二）字符串匹配 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">matrix</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives">
              
                  <span class="site-state-item-count">47</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                
                  <span class="site-state-item-count">19</span>
                  <span class="site-state-item-name">标签</span>
                
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-4"><a class="nav-link" href="#命令行启动"><span class="nav-number">1.</span> <span class="nav-text">命令行启动</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#初始化"><span class="nav-number">2.</span> <span class="nav-text">初始化</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#启动"><span class="nav-number">3.</span> <span class="nav-text">启动</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#namesrv注册"><span class="nav-number">4.</span> <span class="nav-text">namesrv注册</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">matrix</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>
<div class=BbeiAn-info">
  浙ICP备 -
  <a href="http://www.beian.miit.gov.cn">18040498号</a>
  </a>
</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  

    
      <script id="dsq-count-scr" src="https://luyun.disqus.com/count.js" async></script>
    

    
      <script type="text/javascript">
        var disqus_config = function () {
          this.page.url = 'http://yoursite.com/2018/12/17/RocketMQ之旅（六）broker启动/';
          this.page.identifier = '2018/12/17/RocketMQ之旅（六）broker启动/';
          this.page.title = 'RocketMQ之旅（六）broker启动';
        };
        var d = document, s = d.createElement('script');
        s.src = 'https://luyun.disqus.com/embed.js';
        s.setAttribute('data-timestamp', '' + +new Date());
        (d.head || d.body).appendChild(s);
      </script>
    

  




	





  














  





  

  

  

  
  

  

  

  

</body>
</html>
